<template>
  <article class="time-range">
    <n-time-picker
      v-bind="$attrs"
      v-model:formatted-value="startVal"
      :value-format="valueFormat"
      @confirm="updateStart"
      :clearable="false"
    />
    <span class="interval">{{ interval }}</span>
    <n-time-picker
      v-bind="$attrs"
      v-model:formatted-value="endVal"
      :value-format="valueFormat"
      @confirm="updateStart"
      :clearable="false"
    />
  </article>
</template>
<script lang="ts" setup>
  import { isArray } from '@/utils/is';
  import {  ref, watch } from 'vue';

  const props = defineProps({
    modelValue: {
      type: [Array, String],
      default: () => [null, null],
    },
    valueFormat: {
      type: String,
      default: 'HH:mm:ss',
    },
    /**是否转为字符串类型 */
    isString: {
      type: Boolean,
      default: false,
    },
    interval: {
      type: String,
      default: '-',
    },
  });
  const emits = defineEmits(['update:modelValue']);
  const startVal = ref(null);
  const endVal = ref(null);
  function init() {
    const arr = isArray(props.modelValue)
      ? props.modelValue
      : props.modelValue.split(props.interval);
    startVal.value = arr[0] || null;
    endVal.value = arr[1] || null;
  }
  function updateStart(...arg) {
    if (startVal.value && endVal.value) {
      if (endVal.value < startVal.value) {
        emits('update:modelValue', props.isString ? '' : []);
        return (window as any).$message.error('开始时间不能大于结束时间');
      }
      const result = props.isString
        ? startVal.value + props.interval + endVal.value || ''
        : [startVal.value, endVal.value];
      console.log(result);
      emits('update:modelValue', result);
    }
  }
  watch(
    () => props.modelValue,
    () => {
      init();
    },
    {
      immediate: true,
    }
  );
</script>
<style lang="less" scoped>
  .time-range {
    display: flex;
    align-items: center;
  }
  .interval {
    margin: 0 5px;
  }
</style>
